// src/main/java/beer/xz/beer/device/data/ApiConfig.kt
package beer.xz.beer.device.data.api

import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import beer.xz.beer.device.util.Utils
import okhttp3.logging.HttpLoggingInterceptor
import androidx.core.content.edit

object ApiConfig {
    private const val PREFS_NAME = "ApiConfigPrefs"
    private const val KEY_SECRET_KEY = "secretKey"
    private const val KEY_CONTROLLER_CODE = "code"

    const val baseUrl: String = "http://192.168.50.19:8080/" // 默认基础 URL

//        const val baseUrl: String = "http://192.168.3.17:8080/" // 默认基础 URL
    val logLevel: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY // 默认日志级别
    private var secretKey: String? = null
    private var code: String? = null

    private lateinit var sharedPreferences: SharedPreferences

    fun init(context: Context) {
        //for test
        removeAllConfig(context)

        sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        secretKey = sharedPreferences.getString(KEY_SECRET_KEY, null)
        code = sharedPreferences.getString(KEY_CONTROLLER_CODE, null)
        if (!codeExists()) {
            buildCode(context)
        }
        if (!codeExists()) throw RuntimeException("code not found")
    }

    fun removeAllConfig(context: Context) {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit { clear() }
    }

    private fun buildCode(context: Context) {
        code = Utils.getControllerCode(context)
        Log.d("LoadConfig", "================= controller code: $code")
        setCode(code!!)
    }

    private fun saveCode() {
        with(sharedPreferences.edit()) {
            putString(KEY_CONTROLLER_CODE, code)
            apply()
        }
    }

    private fun saveSecretKey() {
        with(sharedPreferences.edit()) {
            putString(KEY_SECRET_KEY, secretKey)
            apply()
        }
    }

    fun codeExists(): Boolean {
        return code != null && code!!.isNotEmpty()
    }

    fun isSecretKeyValid(): Boolean {
        return secretKey != null && secretKey!!.isNotEmpty()
    }

    fun replaceSecretKey(newSecretKey: String) {
        secretKey = newSecretKey
        saveSecretKey()
    }


    fun getCode(): String {
        return code ?: throw RuntimeException("code not exists")
    }

    private fun setCode(newDeviceCode: String) {
        code = newDeviceCode
        saveCode()
    }

    fun getSecretKey(): String? {
        return secretKey
    }
}
